import os
import time

class Logger:
    def __init__(self, log_dir="logs", log_file="scan_log.txt"):
        os.makedirs(log_dir, exist_ok=True)
        self.log_path = os.path.join(log_dir, log_file)

    def log(self, message):
        timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
        log_line = f"[{timestamp}] {message}\n"
        try:
            with open(self.log_path, "a", encoding="utf-8") as f:
                f.write(log_line)
        except Exception as e:
            print(f"日志写入失败: {e}")

        print(log_line.strip())  # 同时输出到控制台


# 创建单例 logger 实例，供全局引用
logger = Logger()
